package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.service.EmpService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("employee")
public class EmpController {

    @Autowired
    EmpService empService;

    /**
     * 员工登录
     */
    @PostMapping("login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session) {
        Employee emp = empService.query().eq("username", employee.getUsername()).one();
        if (emp == null) {
            return R.error("账号不存在！");
        }
        String password1 = employee.getPassword();
        String password2 = emp.getPassword();
        boolean flag = StringUtils.equals(DigestUtils.md5Hex(password1), password2);
        if (!flag) {
            return R.error("密码错误！");
        }
        if (emp.getStatus() == 0) {
            return R.error("账号已被禁用!");
        }

        session.setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    /**
     * 员工退出
     */
    @PostMapping("logout")
    public R<String> logout(HttpSession session) {
        session.invalidate();
        return R.success("");
    }

    /**
     * 新增员工账号信息
     */
    @PostMapping
    public R<String> save(@RequestBody Employee employee) {
        //设置初始密码123456，需要进行md5加密处理
        employee.setPassword(DigestUtils.md5Hex("123456"));
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());

        //获得当前登录用户的id
        //Long empId = (Long) session.getAttribute("employee");
        //employee.setCreateUser(empId);
        //employee.setUpdateUser(empId);
        empService.save(employee);
        return R.success("添加成功!");
    }

    /**
     * 分页查询员工信息
     */
    @GetMapping("page")
    public R<Page<Employee>> page(int page, int pageSize, String name) {
        Page<Employee> pageInfo = new Page<>(page, pageSize);
        empService.query().like(StringUtils.isNotBlank(name), "name", name).orderByDesc("update_time").page(pageInfo);
        return R.success(pageInfo);
    }

    /**
     * 修改：保存员工信息
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee) {
        empService.updateById(employee);
        return R.success("修改成功!");
    }

    /**
     * 修改：回显员工信息
     */
    @GetMapping("{id}")
    public R<Employee> findById(@PathVariable Long id) {
        Employee employee = empService.getById(id);
        return R.success(employee);
    }
}
